import 'package:date_format/date_format.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/commom/Dio.dart';
import 'package:flutter_app/commom/Global.dart';
import 'package:flutter_app/models/ganttChart.dart';
import 'package:flutter_app/routes/GanttRoute.dart';
import 'package:flutter_app/routes/MyGanttRoute.dart';
import 'package:percent_indicator/percent_indicator.dart';

import 'AplResultCard.dart';
import 'HYSizeFit.dart';
import 'WrongAvoid.dart';

class ReleasePdItems extends StatefulWidget {
  ReleasePdItems({
    Key key,
    this.position,
  }) : super(key: key);
  final int position;
  @override
  State<StatefulWidget> createState(){
    return ReleasePdItemsState(position);
  }
}
class ReleasePdItemsState extends State<ReleasePdItems> {

  final int position;
  GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();
  int pdID = 0;
  ReleasePdItemsState(this.position);
  Widget _item_CardBuilder(BuildContext context, int index) {
    return Container(
        //height: HYSizeFit.setPx(350),
        color: Colors.white,
        margin: EdgeInsets.only(top: HYSizeFit.setPx(10)),
        child: IntrinsicHeight(
          child: Column(
            mainAxisAlignment:MainAxisAlignment.spaceBetween,
            crossAxisAlignment:CrossAxisAlignment.center,
            children: [
              Padding(
                padding: EdgeInsets.only(top: HYSizeFit.setPx(10), right: HYSizeFit.setPx(10), left: HYSizeFit.setPx(10)),
                child: Column(
                  children: [
                    Row(
                      mainAxisAlignment:MainAxisAlignment.spaceBetween,
                      crossAxisAlignment:CrossAxisAlignment.center,
                      children: [
                        RichText(
                          text: TextSpan(
                            children: [
                              WidgetSpan(
                                child: Icon(Icons.paste, size: HYSizeFit.setPx(20)),
                              ),
                              TextSpan(
                                text: "   " + Global.findUserProjects.projects[position]['procedures'][index]['pdName'],
                                style: TextStyle(
                                    color: Colors.black,
                                    fontSize: HYSizeFit.setPx(18),
                                    fontWeight: FontWeight.w500
                                ),
                              ),
                            ],
                          ),
                          textDirection: TextDirection.ltr,
                          textAlign: TextAlign.left,
                        ),
                        Text(
                          '状态：' +  Global.findUserProjects.projects[position]['procedures'][index]['pdStatusTxt'],
                          style: TextStyle(
                              color: Colors.black54,
                            fontSize: HYSizeFit.setPx(15)
                          ),
                        )
                      ],
                    ),
                    Padding(
                      padding: EdgeInsets.only(top: HYSizeFit.setPx(8), left: HYSizeFit.setPx(10)),
                    ),
                    Row(
                      mainAxisAlignment:MainAxisAlignment.spaceBetween,
                      //crossAxisAlignment:CrossAxisAlignment.center,
                      children: [
                        CircularPercentIndicator(
                          radius: HYSizeFit.setPx(80),
                          lineWidth: HYSizeFit.setPx(7),
                          animation: true,
                          percent: Global.findUserProjects.projects[position]['procedures'][index]['pdSchedule'] != null ?
                          double.parse(Global.findUserProjects.projects[position]['procedures'][index]['pdSchedule'])/100.0 : 0,
                          //0.3:0,
                          center: new Text(
                            Global.findUserProjects.projects[position]['procedures'][index]['pdSchedule'] != null ?
                            Global.findUserProjects.projects[position]['procedures'][index]['pdSchedule'] + "%" :
                            "0%",
                            style:
                            new TextStyle(fontWeight: FontWeight.normal, fontSize: HYSizeFit.setPx(13)),
                          ),

                          circularStrokeCap: CircularStrokeCap.round,
                          progressColor: Colors.blueGrey,
                        ),
                        Column(
                          crossAxisAlignment:CrossAxisAlignment.start,
                          children: [
                            Text(
                                Global.findUserProjects.projects[position]['procedures'][index]['pdProtime'] !=null ?
                                //"开始时间：" + Global.findUserProcedures.packageProcedures[position]['pdProtime']:
                                "开始：" + formatDate(Global.findUserProjects.projects[position]['procedures'][index]['pdProtime'], [yyyy, '-', mm, '-', dd]) :
                                "未设置",
                                style: TextStyle(
                                  color: Colors.black54,
                                  fontSize: HYSizeFit.setPx(13),
                                )
                            ),
                            Text(
                                Global.findUserProjects.projects[position]['procedures'][index]['pdDeltime'] !=null ?
                                //"开始时间：" + Global.findUserProcedures.packageProcedures[position]['pdProtime']:
                                "交期：" + formatDate(Global.findUserProjects.projects[position]['procedures'][index]['pdDeltime'], [yyyy, '-', mm, '-', dd]) :
                                "未设置",
                                style: TextStyle(
                                  color: Colors.black54,
                                  fontSize: HYSizeFit.setPx(13),
                                )
                            ),
                            Text(
                                Global.findUserProjects.projects[position]['procedures'][index]['pdDemand'] !=null ?
                                //"开始时间：" + Global.findUserProcedures.packageProcedures[position]['pdProtime']:
                                "数量：" + Global.findUserProjects.projects[position]['procedures'][index]['pdDemand'].toString() :
                                "未设置",
                                style: TextStyle(
                                  color: Colors.black54,
                                  fontSize: HYSizeFit.setPx(13),
                                )
                            ),
                            Text(
                                Global.findUserProjects.projects[position]['procedures'][index]['packageUsr']['usrName'] !=null ?
                                //"开始时间：" + Global.findUserProcedures.packageProcedures[position]['pdProtime']:
                                "包揽方：" + Global.findUserProjects.projects[position]['procedures'][index]['packageUsr']['usrName'].toString() :
                                "包揽方：" + "未确定",
                                style: TextStyle(
                                  color: Colors.black54,
                                  fontSize: HYSizeFit.setPx(13),
                                )
                            ),
                          ],
                        ),
                        Column(
                          mainAxisAlignment:MainAxisAlignment.spaceEvenly,
                          crossAxisAlignment:CrossAxisAlignment.center,
                          children: [
                            Container(
                              height: HYSizeFit.setPx(25),
                              padding: EdgeInsets.only(top: HYSizeFit.setPx(5)),
                              child: OutlineButton(
                                  borderSide: BorderSide(
                                    color: Colors.black26,
                                  ),
                                  shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(5)
                                  ),
                                  child: Text(
                                    '催单',
                                    style: TextStyle(
                                        color: Colors.black87,
                                        fontSize: 12
                                    ),
                                  ),
                                  onPressed: ()=>{
                                    if(Global.findUserProjects.projects[position]['procedures'][index]['packageUsr']['usrId'] != null)
                                      _onApplyReminder(context, position, index)
                                  }
                              ),
                            ),
                            Padding(padding: EdgeInsets.only(top: HYSizeFit.setPx(10))),
                            Container(
                              height: HYSizeFit.setPx(25),
                              padding: EdgeInsets.only(top: 5),
                              child: OutlineButton(
                                  borderSide: BorderSide(
                                    color: Colors.black26,
                                  ),
                                  shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(5)
                                  ),
                                  child: Text(
                                    '联系包揽方',
                                    style: TextStyle(
                                        color: Colors.black87,
                                        fontSize: 12
                                    ),
                                  ),
                                  onPressed: () async{
                                    await CommunicationCard(context);
                                  }
                              ),
                            )
                          ],
                        )
                      ],
                    ),
                  ],
                ),
              ),
              Padding(
                padding: EdgeInsets.only(top: HYSizeFit.setPx(10)),
                child: Container(
                    //height: HYSizeFit.setPx(20),
                    decoration: new BoxDecoration(
                      //border: new Border.all(color: Colors.black12, width: 0.5), // 边色与边宽度
                      color: Colors.black12, // 底色
                      borderRadius: BorderRadius.all(Radius.circular(0)), // 也可控件一边圆角大小
                      //borderRadius: new BorderRadius.vertical(top: Radius.elliptical(20, 60)),
                    ),
                    child: Padding(
                      padding: EdgeInsets.only(right: 5, left: 5),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: [
                          Text(
                              Global.findUserProjects.projects[position]['procedures'][index]['bsTxt'] !=null ?
                              //"开始时间：" + Global.findUserProcedures.packageProcedures[position]['pdProtime']:
                              "所需业务：" + Global.findUserProjects.projects[position]['procedures'][index]['bsTxt'] :
                              "未设置",
                              style: TextStyle(
                                color: Colors.black54,
                                fontSize: HYSizeFit.setPx(13),
                              )
                          ),
                        ],
                      ),
                    )
                ),
              ),
            ],
          ),
        )
        );
  }
  @override
  void initState() {
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color.fromRGBO(239, 239, 239, 1),
      appBar: AppBar(
        centerTitle: true,
        title: Text(
            '项目详情',
            style: TextStyle(
              fontSize: 20.0,
              height: 1.2,
            )
        ),
        elevation: 0, //去掉Appbar底部阴影
        brightness: Brightness.light,
        actions: <Widget>[
          //导航栏右侧菜单
          IconButton(
            icon: Icon(
                Icons.bar_chart,
                color: Colors.grey,
              size: 30,
            ),
            onPressed: () => {
              _onGanttChart(context)
            },
          )
        ],
        leading: Builder(builder: (context) {
          return new IconButton(
              icon: new Icon(
                Icons.arrow_back_ios,
                color: Colors.grey,
              ),
              tooltip: '退出',
              onPressed: () => {
                Navigator.pop(context)
              });
        })
      ),
      body: MediaQuery.removePadding(
        child: ListView.builder(
            padding: EdgeInsets.fromLTRB(HYSizeFit.setPx(10), 0, HYSizeFit.setPx(10), HYSizeFit.setPx(10)),
            itemCount: (Global.findUserProjects.projects[position]['procedures'] == null)? 0 : Global.findUserProjects.projects[position]['procedures'].length,
            //itemExtent: HYSizeFit.setPx(160),
            shrinkWrap: true,
            //列表项构造器
            itemBuilder: _item_CardBuilder),
        removeTop: true,
        context: context,
      ),
    );
  }
  void _onGanttChart(BuildContext context){
    bool sameUser = false;
    Global.usersInChart = List();
    Global.dataInChart = List();
    Global.findUserProjects.projects[position]['procedures'].forEach((element) {
      if(element['pdStatus'] == 400){
        Global.dataInChart.add(
            Project(
                id:element['pdId'],
                name:element['pdName'],
                startTime:element['pdProtime'],
                endTime: element['pdDeltime'],
                participants: [0]
            )
        );
      }
      else{
        Global.dataInChart.add(
            Project(
                id:element['pdId'],
                name:element['pdName'],
                startTime:element['pdProtime'],
                endTime: element['pdDeltime'],
                participants: [element['packageUsr']['usrId']]
            )
        );
        sameUser = false;
        Global.usersInChart.forEach((item) {
          if(item.id == element['packageUsr']['usrId'] && item.name == element['packageUsr']['usrName'])
            {
              sameUser = true;
            }
        });
        if(!sameUser){
          Global.usersInChart.add(
              User(
                id: element['packageUsr']['usrId'],
                name: element['packageUsr']['usrName'],
              )
          );
          print('添加用户：' + element['packageUsr']['usrName'] + element['packageUsr']['usrId'].toString());
        }
      }

      pdID = pdID + 1;
    });
    Global.usersInChart.add(
        User(
            id: 0,
            name: '待包揽'
        )
    );

    Navigator.push(
      context,
      new MaterialPageRoute(builder: (context) {
        return new MyGanttChartScreen(
          projects:Global.dataInChart,
          users:Global.usersInChart,
          title: Global.findUserProjects.projects[position]['pjName'] + "-甘特图",
          fromDate: Global.findUserProjects.projects[position]['pjProtime'],
          toDate: Global.findUserProjects.projects[position]['pjDeltime'],
          pjIndex: position,
        );
      }),
    );
  }
  Future<void> _onApplyReminder(BuildContext context, int position, int index)  async {
    var status = await EA(context).reminderApplication(
      Global.findUserProjects.projects[position]['procedures'][index]['packageUsr']['usrId'],
      Global.findUserProjects.projects[position]['procedures'][index]['pdId'],
      Global.findUserProjects.projects[position]['pjId']);
    if(status == 200){
      await AplSuccessedCard(context);
    }
    else await UnderAppFailedCard(context);
  }
}